const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'


const httpInterceptor = {
	// 拦截前出发
	invoke(options:UniApp.RequestOptions){
		// 如果传递过来的url不是以http开头就拼接
		if(!options.url.startsWith('http')){
			options.url = baseUrl + options.url
		}
		// 请求超时时间 默认 60s  现在改完10s
		options.timeout = 10000
		options.header = {
			...options.header,

		}

		
		
	}
}

uni.addInterceptor('request',httpInterceptor)

uni.addInterceptor('uploadFile',httpInterceptor)

interface Data<T>{
	code: string
	msg: string
	result: T
}

export const http = <T> (options:UniApp.RequestOptions)=>{
	// 返回Promise
	return new Promise <Data<T>>((resole,reject)=>{
		 uni.request({
		 	...options,
			
			success(res){
				if(res.statusCode >=200 && res.statusCode <300 ){
					resole(res.data  as Data<T>)
				}else if(res.statusCode == 401){
					reject(res)
				}else {
					uni.showToast({
						icon:'none',
						title:(res.data as Data<T>).msg || '请求错误'
					})
					reject()
				}
			},
			fail(err) {
				uni.showToast({
					icon:'none',
					title:'请检查网络后重新尝试操作'
				})
				reject(err)
			}
			
		 })
	})
}